package com.zyb.org.controller;

import com.zyb.basic.util.AjaxResult;
import com.zyb.basic.util.QueryResult;
import com.zyb.org.domain.Employee;
import com.zyb.org.query.EmployeeQuery;
import com.zyb.org.service.IEmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController //@Controller+@ResponseBody(转换json)
@RequestMapping("/emp")
@Api(value = "用户的API",description="用户相关的CRUD功能")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询" )
    public Employee queryOne(@PathVariable @ApiParam(name="ID属性",required = true)  Long id){
        return employeeService.loadOne(id);
    }
    @GetMapping
    public List<Employee> queryAll(){
        return employeeService.loadAll();
    }
    //axios get不支持传对象
    @PostMapping
    public QueryResult<Employee> listPage(@RequestBody EmployeeQuery query){
        return  employeeService.queryPage(query);
    }

    @DeleteMapping("/{id}")
    public AjaxResult deleteById(@PathVariable Long id){
        try {
            employeeService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    /*修改和新增
    * put请求 http://localhost:8080/dept
    * */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Employee employee){
        try {
            if(employee.getId() == null){
                employeeService.add(employee);
            }else {
                employeeService.update(employee);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }

    /*批量删除*/
    @PatchMapping
    public AjaxResult batchDelete(@RequestBody List<Long> ids){
        try {
            employeeService.batchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }
}
